#include "LineDescParser.h"

#include "LineEndParser.h"
#include "LinePropertyParser.h"
#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LineDescParser::LineDescParser(
    LineEndParser *&_lineEndParser
    , DoubleParser *&_lineWidthParser
    , LinePropertyParser *&_linePropertyParser
):    m_lineEndParser(_lineEndParser)
    , m_lineWidthParser(_lineWidthParser)
    , m_linePropertyParser(_linePropertyParser)
{

}

bool LineDescParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new LineDesc());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("lineEnd")))
    {
        data = reader->attributes().value(QStringLiteral("lineEnd"));
        if (!m_lineEndParser->parse(reader, data))
            return false;
        m_result->lineEnd = m_lineEndParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("lineEnd: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("lineWidth")))
    {
        data = reader->attributes().value(QStringLiteral("lineWidth"));
        if (!m_lineWidthParser->parse(reader, data))
            return false;
        m_result->lineWidth = m_lineWidthParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("lineWidth: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("lineProperty")))
    {
        data = reader->attributes().value(QStringLiteral("lineProperty"));
        if (!m_linePropertyParser->parse(reader, data))
            return false;
        m_result->linePropertyOptional = Optional<LineProperty>(m_linePropertyParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

LineDesc *LineDescParser::result()
{
    return m_result.take();
}

}